package com.luohh.treeroom.service.impl;

import com.luohh.treeroom.dto.BaseResult;
import com.luohh.treeroom.service.EmailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailSendException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * \* Created with IntelliJ IDEA.
 * \* User: 罗辉煌
 * \* Date: 2020/2/8
 * \* Time: 22:35
 * \* To change this template use File | Settings | File Templates.
 * \* Description:
 * \
 */
@Service
//@Transactional
@Slf4j
//@EnableAsync
public class EmailServiceImpl implements EmailService {

    @Autowired
    JavaMailSenderImpl mailSender;

    /**
     * 从配置文件中获取发件人
     */
    @Value("${spring.mail.username}")
    private String sender;

    /**
     * 邮件发送
     * @param receiver 收件人
     * @param verCode 验证码
     * @throws MailSendException 邮件发送错误
     */
    @Async
    public  BaseResult send(String email,String verCode) throws MailSendException {
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setSubject("验证码");	//设置邮件标题
            message.setText("尊敬的用户,您好:\n"
                    + "\n本次请求的邮件验证码为:" + verCode + ",本验证码1分钟内有效，请及时输入。（请勿泄露此验证码）\n"
                    + "\n如非本人操作，请忽略该邮件。\n(这是一封自动发送的邮件，请不要直接回复哦小强强）");	//设置邮件正文
            message.setTo(email);	//设置收件人
            message.setFrom(sender);	//设置发件人
            mailSender.send(message);	//发送邮件
            return new BaseResult();
        }catch (Exception e){
            System.out.println(e);
            return new BaseResult("0", "发送失败" ,e);
        }

    }

}